<?php
namespace app\index\controller;

use app\index\model\ContractCaiListModel;
use app\index\model\ContractCaiModel;
use app\index\model\DeviceJieModel;
use app\index\model\DeviceLinModel;
use app\index\model\EnginBudbianListModel;
use app\index\model\EnginBudbianModel;
use app\index\model\EnginBudgetListModel;
use app\index\model\EnginBudgetModel;
use app\index\model\EnginBudshouModel;
use app\index\model\EnginBudsubModel;
use app\index\model\EnginModel;
use app\index\model\FlowBillModel;
use app\index\model\FlowLogModel;
use app\index\model\LabourJieModel;
use app\index\model\LabourLingModel;
use app\index\model\LabourShenModel;
use app\index\model\PaymentBaoListModel;
use app\index\model\PaymentBaoModel;
use app\index\model\PaymentEnginModel;
use app\index\model\StuffJieModel;
use app\index\model\StuffRuModel;
use app\index\model\SubbaoJieModel;
use app\index\model\SubbaoShenModel;
use app\index\relevan\EnginRelevan;
use app\index\service\BudgetService;
use app\index\service\ContractService;
use app\index\service\EnginService;
use app\index\service\FlowService;
use app\index\service\MenuService;
use app\index\service\OptService;
use app\index\service\UserService;
use think\Db;
use think\Request;

class Budget extends Common
{

    public function list_engin_budsub(Request $request){
        $pid = $request->param('pid', 0, 'int');

        if($pid > 0){
            $data['data'] = (new BudgetService())->get_budsub_all($pid);

        }else{
            $data['data'] = [];
        }

        $data['butauth'] = (new MenuService())->get_butauth('engin_budsub');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_budsub_nav(Request $request){
        $data = EnginBudsubModel::field('id,name as title')
            ->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'pid'=>0])
            ->order('sort ASC')->select()->toArray();
        foreach ($data as &$item){
            $item['spread'] = true;
        }
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_engin_budsub(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }
            if((new BudgetService())->check_budsub_name($param['name'], $param['topid'])){
                return outputJson(4000, '名称已存在');
            }

            if(strpos($param['name'],'/') !== false){
                return outputJson(4000, '名称中不能包含特殊字符“/”');
            }

            $param['pid'] = $param['topid'];
            $maxSort = EnginBudsubModel::where(['topid'=>$param['topid'],'pid'=>$param['pid']])->max('sort');
            $param['sort'] = $maxSort+1;



            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);

            Db::startTrans();
            try {
                $id = EnginBudsubModel::insertGetId($param);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_budsub', $id, '成本科目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $topid = $request->get('topid', 0, 'int');
            $data['data'] = EnginBudsubModel::where(['id'=>$topid])->find();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function addson_engin_budsub(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }

            $pidinfo = EnginBudsubModel::where(['id'=>$param['id']])->find();
            if((new BudgetService())->check_budsub_name($param['name'], $pidinfo['topid'])){
                return outputJson(4000, '名称已存在');
            }

            if(strpos($param['name'],'/') !== false){
                return outputJson(4000, '名称中不能包含特殊字符“/”');
            }

            $param['pid'] = $pidinfo['id'];
            $param['topid'] = $pidinfo['topid'];

            $maxSort = EnginBudsubModel::where(['topid'=>$pidinfo['topid'],'pid'=>$param['id']])->max('sort');
            $param['sort'] = $maxSort+1;

            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);
            unset($param['id']);

            Db::startTrans();
            try {
                $id = EnginBudsubModel::insertGetId($param);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_budsub', $id, '成本科目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginBudsubModel::where(['id'=>$id])->find();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function edit_engin_budsub(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }

            $pidinfo = EnginBudsubModel::where(['id'=>$param['id']])->find();
            if((new BudgetService())->check_budsub_name($param['name'], $pidinfo['topid'], $param['id'])){
                return outputJson(4000, '名称已存在');
            }

            if($param['pid'] == $param['id']){
                unset($param['pid']);
            }


            if(strpos($param['name'],'/') !== false){
                return outputJson(4000, '名称中不能包含特殊字符“/”');
            }

            $param['comid'] = $this->userinfo['comid'];
            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);

            Db::startTrans();
            try {
                EnginBudsubModel::update($param);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin_budsub', $param['id'], '成本科目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data = EnginBudsubModel::where(['id'=>$id])->find();
            $data['pidArr'] = (new BudgetService())->get_budsub_all();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function move_engin_budsub(Request $request){
        if($request->isPost()){
            $id = $request->post('id', 0, 'int');
            $type = $request->post('type', 0, 'int');

            $data = EnginBudsubModel::where(['id'=>$id])->find();
            if(!$data){
                return outputJson(2000,lang('code_2000'));
            }

            $list = EnginBudsubModel::where(['pid'=>$data['pid'],'topid'=>$data['topid'],'deleted_user'=>0])->order('sort ASC')->column('id');
            if(count($list) < 2){
                return outputJson(2000,lang('code_2000'));
            }

            $info = [];
            if($type == 1){
                foreach ($list as $k=>$opid){
                    if($opid == $data['id']){
                        if($k == 0){
                            $info[] = $opid;
                        }else{
                            $info[$k-1] = $opid;
                            $info[$k] = $list[$k-1];
                        }
                    }else{
                        $info[] = $opid;
                    }
                }
            }elseif($type == 2){
                foreach ($list as $k=>$opid){
                    if($k > 0){
                        if($list[$k-1] == $data['id']){
                            $info[$k-1] = $opid;
                            $info[$k] = $list[$k-1];
                        }else{
                            $info[] = $opid;
                        }
                    }else{
                        $info[] = $opid;
                    }
                }
            }else{
                $info = $list;
            }

            Db::startTrans();
            try {
                $sort = 1;
                foreach ($info as $_opid){
                    EnginBudsubModel::where(['id'=>$_opid])->update(['sort'=>$sort]);
                    $sort++;
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(2000,lang('code_2000'));
            }
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function del_engin_budsub(Request $request){
        $param = $request->post();
        $data = EnginBudsubModel::where(['id'=>$param['id']])->find();
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        if( EnginBudsubModel::where(['pid'=>$data['id'],'deleted_user'=>0])->find() ){
            return outputJson(4000, '该数据下存在子级数据，不能删除');
        }

        $yong = EnginBudgetListModel::alias('list')
            ->join('engin_budget bud','bud.id=list.budid')
            ->where(['bud.comid'=>$this->userinfo['comid'],'bud.deleted_user'=>0,'bud.isturn'=>1])
            ->where('bud.status','in',[0,1])
            ->where('list.subid','=',$data['id'])
            ->find();
        if($yong){
            return outputJson(4000, '该科目下存在预算明细数据，不能删除');
        }


        Db::startTrans();
        try {
            EnginBudsubModel::where(['id'=>$data['id']])->delete();
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin_budsub', $data['id'], '成本科目');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }


    public function list_engin_budshou(Request $request){
        $pid = $request->param('pid', 0, 'int');

        if($pid > 0){
            $data['data'] = (new BudgetService())->get_budshou_all($pid);

        }else{
            $data['data'] = [];
        }

        $data['butauth'] = (new MenuService())->get_butauth('engin_budshou');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function list_engin_budshou_nav(Request $request){
        $data = EnginBudshouModel::field('id,name as title')
            ->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'pid'=>0])
            ->order('sort ASC')->select()->toArray();
        foreach ($data as &$item){
            $item['spread'] = true;
        }
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_engin_budshou(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }
            if((new BudgetService())->check_budshou_name($param['name'], $param['topid'])){
                return outputJson(4000, '名称已存在');
            }

            if(strpos($param['name'],'/') !== false){
                return outputJson(4000, '名称中不能包含特殊字符“/”');
            }

            $param['pid'] = $param['topid'];
            $maxSort = EnginBudshouModel::where(['topid'=>$param['topid'],'pid'=>$param['pid']])->max('sort');
            $param['sort'] = $maxSort+1;




            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);

            Db::startTrans();
            try {
                $id = EnginBudshouModel::insertGetId($param);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_budshou', $id, '收入科目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $topid = $request->get('topid', 0, 'int');
            $data['data'] = EnginBudshouModel::where(['id'=>$topid])->find();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function addson_engin_budshou(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }

            $pidinfo = EnginBudshouModel::where(['id'=>$param['id']])->find();
            if((new BudgetService())->check_budshou_name($param['name'], $pidinfo['topid'])){
                return outputJson(4000, '名称已存在');
            }

            if(strpos($param['name'],'/') !== false){
                return outputJson(4000, '名称中不能包含特殊字符“/”');
            }

            $param['pid'] = $pidinfo['id'];
            $param['topid'] = $pidinfo['topid'];

            $maxSort = EnginBudshouModel::where(['topid'=>$pidinfo['topid'],'pid'=>$param['id']])->max('sort');
            $param['sort'] = $maxSort+1;

            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);
            unset($param['id']);

            Db::startTrans();
            try {
                $id = EnginBudshouModel::insertGetId($param);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_budshou', $id, '收入科目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginBudshouModel::where(['id'=>$id])->find();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function edit_engin_budshou(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $old = EnginBudshouModel::where(['id'=>$param['id']])->find();
            if($old['isdea'] > 0){
                return outputJson(4000, '系统预设数据，不能编辑');
            }

            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }

            $pidinfo = EnginBudshouModel::where(['id'=>$param['id']])->find();
            if((new BudgetService())->check_budshou_name($param['name'], $pidinfo['topid'], $param['id'])){
                return outputJson(4000, '名称已存在');
            }

            if($param['pid'] == $param['id']){
                unset($param['pid']);
            }

            if(strpos($param['name'],'/') !== false){
                return outputJson(4000, '名称中不能包含特殊字符“/”');
            }

            $param['comid'] = $this->userinfo['comid'];
            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);



            Db::startTrans();
            try {
                EnginBudshouModel::update($param);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin_budshou', $param['id'], '收入科目');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data = EnginBudshouModel::where(['id'=>$id])->find();
            $data['pidArr'] = (new BudgetService())->get_budshou_all();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function move_engin_budshou(Request $request){
        if($request->isPost()){
            $id = $request->post('id', 0, 'int');
            $type = $request->post('type', 0, 'int');

            $data = EnginBudshouModel::where(['id'=>$id])->find();
            if(!$data){
                return outputJson(2000,lang('code_2000'));
            }

            $list = EnginBudshouModel::where(['pid'=>$data['pid'],'topid'=>$data['topid'],'deleted_user'=>0])->order('sort ASC')->column('id');
            if(count($list) < 2){
                return outputJson(2000,lang('code_2000'));
            }

            $info = [];
            if($type == 1){
                foreach ($list as $k=>$opid){
                    if($opid == $data['id']){
                        if($k == 0){
                            $info[] = $opid;
                        }else{
                            $info[$k-1] = $opid;
                            $info[$k] = $list[$k-1];
                        }
                    }else{
                        $info[] = $opid;
                    }
                }
            }elseif($type == 2){
                foreach ($list as $k=>$opid){
                    if($k > 0){
                        if($list[$k-1] == $data['id']){
                            $info[$k-1] = $opid;
                            $info[$k] = $list[$k-1];
                        }else{
                            $info[] = $opid;
                        }
                    }else{
                        $info[] = $opid;
                    }
                }
            }else{
                $info = $list;
            }

            Db::startTrans();
            try {
                $sort = 1;
                foreach ($info as $_opid){
                    EnginBudshouModel::where(['id'=>$_opid])->update(['sort'=>$sort]);
                    $sort++;
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(2000,lang('code_2000'));
            }
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function del_engin_budshou(Request $request){
        $param = $request->post();
        $data = EnginBudshouModel::where(['id'=>$param['id']])->find();
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }
        if($data['isdea'] > 0){
            return outputJson(4000, '系统预设数据，不能删除');
        }


        if( EnginBudshouModel::where(['pid'=>$data['id'],'deleted_user'=>0])->find() ){
            return outputJson(4000, '该数据下存在子级数据，不能删除');
        }

        $yong = EnginBudgetListModel::alias('list')
            ->join('engin_budget bud','bud.id=list.budid')
            ->where(['bud.comid'=>$this->userinfo['comid'],'bud.deleted_user'=>0,'bud.isturn'=>1])
            ->where('bud.status','in',[0,1])
            ->where('list.subid','=',$data['id'])
            ->find();
        if($yong){
            return outputJson(4000, '该科目下存在预算明细数据，不能删除');
        }


        Db::startTrans();
        try {
            EnginBudshouModel::where(['id'=>$data['id']])->delete();
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin_budshou', $data['id'], '收入科目');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }



    public function list_engin_budget(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['bud.deleted_user','=', 0];
        $where[] = ['bud.comid','=',$this->userinfo['comid']];
        $where[] = ['bud.isturn','=',1];
        $where[] = ['bud.status','in',[0,1]];

        if(isset($param['enginid']) && !empty($param['enginid'])){
            $where[] = ['bud.enginid','=', $param['enginid']];
        }
        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['e.enginname|bud.name|bud.bianer','like', '%'.$param['keyword'].'%'];
        }
        if(isset($param['enginname']) && !empty($param['enginname'])){
            $where[] = ['e.name','like', '%'.$param['enginname'].'%'];
        }
        if(isset($param['enginnumber']) && !empty($param['enginnumber'])){
            $where[] = ['e.number','like', '%'.$param['enginnumber'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['bud.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['bud.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['bianer']) && !empty($param['bianer'])){
            $where[] = ['bud.bianer','like', '%'.$param['bianer'].'%'];
        }
        if(isset($param['biandt']) && !empty($param['biandt'])){
            $where[] = ['bud..biandt','between', explode(' - ', $param['biandt'])];
        }
        if(isset($param['money']) && !empty($param['money'])){
            $where[] = ['bud.money','like', '%'.$param['money'].'%'];
        }

        if(isset($param['chanid']) && !empty($param['chanid'])){
            $where[] = ['e.chanid','=', $param['chanid']];
        }
        if(isset($param['business']) && !empty($param['business'])){
            $where[] = ['e.business','=', $param['business']];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['bud.status','=', $param['status']];
        }

        $data['chanid'] = (new UserService())->get_chaninfo_all();;
        $data['is_chanid'] = isset($param['chanid']) ? $param['chanid'] : '';

        $data['data'] = EnginBudgetModel::alias('bud')
            ->field('bud.*,e.name as enginname')
            ->join('engin e','e.id=bud.enginid')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin_budget', 'bud'))
            ->order('bud.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('engin_budget');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function getbudsub_engin_budget(Request $request){
        $data = (new BudgetService())->get_budsubquan_all();
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_engin_budget(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['enginid'])){
                return outputJson(4000, '请选择工程名称');
            }
            if(empty($param['name'])){
                return outputJson(4000, '请输入预算主题');
            }

            $exist = EnginBudgetModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'isturn'=>1,'enginid'=>$param['enginid']])
                ->where('status','in',[0,1])->find();
            if($exist){
                return outputJson(4000, '该项目下存在预算，请勿重复添加');
            }


            $param['comid'] = $this->userinfo['comid'];
            $param['status'] = 1;
            $param['isturn'] = 1;
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            $param['deptid'] = $this->userinfo['deptid'];
            $param['chanid'] = (new UserService())->get_user_chanid();


            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            $list = array_filter($param['list']);
            unset($param['list']);
            if(count($list) < 1){
                return outputJson(4000, '请输入预算明细');
            }
            $subSort = array_column($list,'subid');
            array_multisort($subSort,SORT_DESC,$list);

            Db::startTrans();
            try {
                $id = EnginBudgetModel::insertGetId($param);

                foreach($list as $vv){
                    $vv['budid'] = $id;
                    EnginBudgetListModel::insert($vv);
                }

                (new OptService())->relation_file($files,'engin_budget',$id);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'engin_budget', $id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_budget', $id, '成本预算');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['bianer'] = $this->userinfo['realname'];
            $data['biandt'] = date("Y-m-d");
            $data['navarr'] = EnginBudsubModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'pid'=>0])
                ->where('name','neq','公司费用')
                ->select()->toArray();


            foreach ($data['navarr'] as &$item){
                $item['children'] = EnginBudsubModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
                    ->where('id='.$item['id'].' or topid='.$item['id'])->column('id');
            }
            $data['files'] = (new OptService())->get_file('engin_budget');
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function edit_engin_budget(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $old = EnginBudgetModel::where(['id'=>$param['id']])->find();

            if(empty($param['name'])){
                return outputJson(4000, '请输入预算主题');
            }

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            $list = array_filter($param['list']);
            unset($param['list']);
            if(count($list) < 1){
                return outputJson(4000, '请输入预算明细');
            }

            $subSort = array_column($list,'subid');
            array_multisort($subSort,SORT_DESC,$list);



            Db::startTrans();
            try {
                EnginBudgetModel::update($param);
                EnginBudgetListModel::where(['budid'=>$param['id']])->delete();
                foreach($list as $vv){
                    $vv['budid'] = $param['id'];
                    EnginBudgetListModel::insert($vv);
                }

                (new OptService())->relation_file($files,'engin_budget',$param['id']);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'engin_budget', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'engin_budget', $param['id'], '成本预算');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginBudgetModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

            $engininfo = EnginModel::get_info_by_pk($data['data']['enginid']);
            $data['engininfo'] = $engininfo;

            $list = EnginBudgetListModel::where(['budid'=>$data['data']['id']])->select()->toArray();
            foreach ($list as &$vvv){
                $vvv['subname'] = (new BudgetService())->get_subid_quanname($vvv['subid']);
            }
            $data['list'] = $list;

            $data['navarr'] = EnginBudsubModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'pid'=>0])
                ->where('name','neq','公司费用')
                ->select()->toArray();
            foreach ($data['navarr'] as &$item){
                $item['children'] = EnginBudsubModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
                    ->where('id='.$item['id'].' or topid='.$item['id'])->column('id');
            }
            $data['files'] = (new OptService())->get_file('engin_budget', $data['data']['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function del_engin_budget(Request $request){
        $param = $request->post();
        $data = EnginBudgetModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            FlowBillModel::where(['id'=>$data['billid']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            EnginBudgetModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin_budget', $data['id'], '成本预算');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function show_engin_budget(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = EnginBudgetModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }

        $data['engininfo'] = (new EnginService())->get_engin_showinfo($data['data']['enginid']);
        $data['engininfo']['business_name'] = $data['engininfo']['business'] == 1 ? '自营' : '联营';

        $data['bianinfo'] = EnginBudbianModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
            ->where(['budgetid'=>$data['data']['id'],'isturn'=>1,'status'=>1])->find();



        $info = EnginBudgetListModel::where(['budid'=>$data['data']['id']])->select()->toArray();
        $listid = array_column($info,'id');
        $yuwainum = 0;
        $caiinfo = ContractCaiModel::where(['deleted_user'=>0,'isturn'=>1,'status'=>1,'enginid'=>$data['data']['enginid']])->column('id');
        foreach ($caiinfo as $caiid){
            $yuwainum += ContractCaiListModel::where(['caiid'=>$caiid])->where('listid','not in', $listid)->count();
        }
        $data['data']['yuwainum'] = $yuwainum;

        $subidArr = [];


        $data['data']['zhanfee'] = 0;
        $data['data']['shengfee'] = 0;


        foreach ($info as &$vv){
            $vv['subid_name'] = $vv['name'];
            $vv['name'] = '#.预算项';
            $vv['zhannum'] = ContractCaiListModel::alias('list')
                ->join('contract_cai cai','cai.id = list.caiid')
                ->where(['cai.deleted_user'=>0,'cai.isturn'=>1])
                ->where('cai.status','in',[0,1])
                ->where(['list.listid'=>$vv['id']])
                ->sum('list.num');
            $vv['shengnum'] = round($vv['num'] - $vv['zhannum'], 2);

            $vv['zhanmoney'] = ContractCaiListModel::alias('list')
                ->join('contract_cai cai','cai.id = list.caiid')
                ->where(['cai.deleted_user'=>0,'cai.isturn'=>1])
                ->where('cai.status','in',[0,1])
                ->where(['list.listid'=>$vv['id']])
                ->sum('list.money');

            $vv['avamoney'] = 0;
            if($vv['zhannum'] != 0){
                $vv['avamoney'] = round($vv['zhanmoney'] / $vv['zhannum'], 2);
            }

            $vv['shengmoney'] = round($vv['money'] - $vv['zhanmoney'], 2);

            $data['data']['zhanfee'] += $vv['zhanmoney'];
            $data['data']['shengfee'] += $vv['shengmoney'];

            if(isset($subidArr[$vv['subid']])){
                $subidArr[$vv['subid']]['money'] += $vv['money'];
                $subidArr[$vv['subid']]['zhanmoney'] += $vv['zhanmoney'];
                $subidArr[$vv['subid']]['shengmoney'] += $vv['shengmoney'];
            }else{
                $subidArr[$vv['subid']] = [
                    'money' => $vv['money'],
                    'zhanmoney' => $vv['zhanmoney'],
                    'shengmoney' => $vv['shengmoney'],
                ];
            }


            //合同项
            $children = ContractCaiListModel::alias('list')
                ->field('list.*')
                ->join('contract_cai cai','cai.id = list.caiid')
                ->where(['cai.deleted_user'=>0,'cai.isturn'=>1])
                ->where('cai.status','in',[0,1])
                ->where(['list.listid'=>$vv['id']])
                ->select()->toArray();
            foreach ($children as &$vvvv){
                $vvvv['ishetong'] = 1;
                $vvvv['subid_name'] = $vvvv['name'];
                $vvvv['name'] = '#.合同项';

                $vvvv['zhannum'] = $vvvv['num'];
                $vvvv['num'] = '/';

                $vvvv['zhanmoney'] = $vvvv['money'];
                $vvvv['money'] = '/';

                $vvvv['avamoney'] = $vvvv['price'];
                $vvvv['price'] = '/';


                $vvvv['shengnum'] = '/';
                $vvvv['shengmoney'] = '/';
            }
            $vv['children'] = $children;
        }

        $data['data']['zhanfee'] = round($data['data']['zhanfee'], 2);
        $data['data']['shengfee'] = round($data['data']['shengfee'], 2);


        $zhongArr = [];
        foreach ($subidArr as $k=>$v){
            $arr = (new BudgetService())->get_shangji_dingji_data($k, $v);
            foreach ($arr as $kk=>$vvvvv){
                if(isset($zhongArr[$kk])){
                    $zhongArr[$kk]['money'] += $vvvvv['money'];
                    $zhongArr[$kk]['zhanmoney'] += $vvvvv['zhanmoney'];
                    $zhongArr[$kk]['shengmoney'] += $vvvvv['shengmoney'];
                }else{
                    $zhongArr[$kk] = $vvvvv;
                }
            }
        }


        foreach ($zhongArr as &$val){
            $val['money'] = round($val['money'], 2);
            $val['zhanmoney'] = round($val['zhanmoney'], 2);
            $val['shengmoney'] = round($val['shengmoney'], 2);
        }

        foreach ($zhongArr as &$item){
            $item['children'] = [];
            $item['shengmoney'] = round($item['shengmoney'], 2);
            $item['last'] = false;

            foreach ($info as $vvv){
                if($vvv['subid'] == $item['id']){
                    $item['last'] = true;
                    $item['children'][] = $vvv;
                }
            }
        }

        $list = array2tree($zhongArr, 'id', 'pid', 'children');
        $subSort = array_column($list,'id');
        array_multisort($subSort,SORT_ASC,$list);

        $data['list'] = $list;
        $data['files'] = (new OptService())->get_file('engin_budget', $data['data']['id']);
        $data['billinfo'] = (new FlowService())->get_flow_show_info($data['data']['billid']);
        return outputJson(2000,lang('code_2000'), $data);
    }

    public function list_engin_budget_zhi(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['bud.deleted_user','=', 0];
        $where[] = ['bud.comid','=',$this->userinfo['comid']];
        $where[] = ['bud.isturn','=',1];
        $where[] = ['bud.status','=',1];


        if(isset($param['enginname']) && !empty($param['enginname'])){
            $where[] = ['e.name','like', '%'.$param['enginname'].'%'];
        }
        if(isset($param['enginnumber']) && !empty($param['enginnumber'])){
            $where[] = ['e.number','like', '%'.$param['enginnumber'].'%'];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['bud.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['number']) && !empty($param['number'])){
            $where[] = ['bud.number','like', '%'.$param['number'].'%'];
        }
        if(isset($param['bianer']) && !empty($param['bianer'])){
            $where[] = ['bud.bianer','like', '%'.$param['bianer'].'%'];
        }
        if(isset($param['biandt']) && !empty($param['biandt'])){
            $where[] = ['bud..biandt','between', explode(' - ', $param['biandt'])];
        }
        if(isset($param['money']) && !empty($param['money'])){
            $where[] = ['bud.money','like', '%'.$param['money'].'%'];
        }


        $data['data'] = EnginBudgetModel::alias('bud')
            ->field('bud.*,e.name as enginname')
            ->join('engin e','e.id=bud.enginid')
            ->where($where)
            ->order('bud.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['caimoney'] = 0;
                $list = EnginBudgetListModel::where(['budid'=>$item['id']])->column('id');
                foreach ($list as $listid){
                    $item['caimoney'] += ContractCaiListModel::alias('list')
                        ->join('contract_cai cai','cai.id=list.caiid')
                        ->where(['cai.deleted_user'=>0,'cai.isturn'=>1])
                        ->where('cai.status','in',[0,1])
                        ->where('list.listid','=',$listid)
                        ->sum('list.money');
                }

                $item['sheng'] = $item['money'] - $item['caimoney'];
                $item['chaorate'] = '';
                if($item['sheng'] < 0){
                    if($item['money'] == 0){
                        $item['chaorate'] = '';
                    }else{
                        $item['chaorate'] = round(-$item['sheng']/$item['money']*100,2);
                    }
                }

                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('engin_budget_zhi');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function show_engin_budget_zhi(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = EnginBudgetModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }

        $data['engininfo'] = (new EnginService())->get_engin_showinfo($data['data']['enginid']);

        $info = EnginBudgetListModel::where(['budid'=>$data['data']['id']])->select()->toArray();
        $listid = array_column($info,'id');
        $yuwainum = 0;
        $caiinfo = ContractCaiModel::where(['deleted_user'=>0,'isturn'=>1,'status'=>1,'enginid'=>$data['data']['enginid']])->column('id');
        foreach ($caiinfo as $caiid){
            $yuwainum += ContractCaiListModel::where(['caiid'=>$caiid])->where('listid','not in', $listid)->count();
        }
        $data['data']['yuwainum'] = $yuwainum;

        $subidArr = [];


        $data['data']['shengfee'] = 0;


        foreach ($info as &$vv){
            $vv['subid_name'] = $vv['name'];
            $vv['name'] = '#.预算项';
            $vv['zhannum'] = ContractCaiListModel::alias('list')
                ->join('contract_cai cai','cai.id = list.caiid')
                ->where(['cai.deleted_user'=>0,'cai.isturn'=>1])
                ->where('cai.status','in',[0,1])
                ->where(['list.listid'=>$vv['id']])
                ->sum('list.num');
            $vv['shengnum'] = $vv['num'] - $vv['zhannum'];

            $vv['zhanmoney'] = ContractCaiListModel::alias('list')
                ->join('contract_cai cai','cai.id = list.caiid')
                ->where(['cai.deleted_user'=>0,'cai.isturn'=>1])
                ->where('cai.status','in',[0,1])
                ->where(['list.listid'=>$vv['id']])
                ->sum('list.money');
            $vv['shengmoney'] = $vv['money'] - $vv['zhanmoney'];

            $data['data']['shengfee'] += $vv['shengmoney'];

            if(isset($subidArr[$vv['subid']])){
                $subidArr[$vv['subid']]['money'] += $vv['money'];
                $subidArr[$vv['subid']]['zhanmoney'] += $vv['zhanmoney'];
                $subidArr[$vv['subid']]['shengmoney'] += $vv['shengmoney'];
            }else{
                $subidArr[$vv['subid']] = [
                    'money' => $vv['money'],
                    'zhanmoney' => $vv['zhanmoney'],
                    'shengmoney' => $vv['shengmoney'],
                ];
            }

            //合同项
            $children = ContractCaiListModel::alias('list')
                ->field('list.*')
                ->join('contract_cai cai','cai.id = list.caiid')
                ->where(['cai.deleted_user'=>0,'cai.isturn'=>1])
                ->where('cai.status','in',[0,1])
                ->where(['list.listid'=>$vv['id']])
                ->select()->toArray();
            foreach ($children as &$vvvv){
                $vvvv['subid_name'] = $vvvv['name'];
                $vvvv['name'] = '#.合同项';
                $vvvv['zhannum'] = '/';
                $vvvv['zhanmoney'] = '/';
                $vvvv['shengnum'] = '/';
                $vvvv['shengmoney'] = '/';
            }
            $vv['children'] = $children;
        }

        $data['data']['shengfee'] = round($data['data']['shengfee'], 2);


        $zhongArr = [];
        foreach ($subidArr as $k=>$v){
            $arr = (new BudgetService())->get_shangji_dingji_data($k, $v);
            foreach ($arr as $kk=>$vvvvv){
                if(isset($zhongArr[$kk])){
                    $zhongArr[$kk]['money'] += $vvvvv['money'];
                    $zhongArr[$kk]['zhanmoney'] += $vvvvv['zhanmoney'];
                    $zhongArr[$kk]['shengmoney'] += $vvvvv['shengmoney'];
                }else{
                    $zhongArr[$kk] = $vvvvv;
                }
            }
        }


        foreach ($zhongArr as &$item){
            $item['children'] = [];
            foreach ($info as $vvv){
                if($vvv['subid'] == $item['id']){
                    $item['children'][] = $vvv;
                }
            }
        }

        $data['list'] = array2tree($zhongArr, 'id', 'pid', 'children');

        $data['files'] = (new OptService())->get_file('engin_budget', $data['data']['id']);
        $data['billinfo'] = (new FlowService())->get_flow_show_info($data['data']['billid']);

        $data['butauth'] = (new MenuService())->get_butauth('engin_budget_zhi');
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function engin_budget_zhi_yuwai(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $old = ContractCaiModel::where(['id'=>$param['id']])->find();

            $list = array_filter($param['list']);
            unset($param['list']);


            Db::startTrans();
            try {

                foreach($list as $vv){
                    ContractCaiListModel::update($vv);
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = EnginBudgetModel::where(['id'=>$id])->find();
            if(!$data['data']){
                return outputJson(4000, lang('code_4000'));
            }

//            $listid = EnginBudgetListModel::where(['budid'=>$data['data']['id']])->column('id');

            $list =  ContractCaiListModel::alias('list')
                ->field('list.*,cai.id as caiid,cai.name as cai_name,cai.caihetype as cai_caihetype,cai.gonger as cai_gonger')
                ->join('contract_cai cai','cai.id = list.caiid')
                ->where(['cai.deleted_user'=>0,'cai.isturn'=>1,'cai.status'=>1,'cai.enginid'=>$data['data']['enginid']])
//                ->where('list.listid','not in',$listid)
                ->order('listid ASC')
                ->select()->toArray();
            foreach ($list as &$item){
                $item['subname'] = '';
                $item['guiname'] = '';
                $listinfo = EnginBudgetListModel::where(['id'=>$item['listid']])->find();
                if($listinfo){
                    $item['subname'] = (new BudgetService())->get_subid_quanname($listinfo['subid']);
                    $item['guiname'] = $listinfo['name'];
                }

                $item['cai_caihetype_name'] = (new ContractService())->get_contract_caihetype_name($item['cai_caihetype']);
            }
            $data['list'] = $list;
            return outputJson(2000,lang('code_2000'),$data);
        }
    }


    public function list_engin_cheng_zhi(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['bud.deleted_user','=', 0];
        $where[] = ['bud.comid','=',$this->userinfo['comid']];
        $where[] = ['bud.isturn','=',1];
        $where[] = ['bud.status','=',1];

        if(isset($param['enginname']) && !empty($param['enginname'])){
            $where[] = ['e.name','like', '%'.$param['enginname'].'%'];
        }


        $arr = [
            'cai' =>  ['name'=>'材料费','shiid'=>1],
            'ren' =>  ['name'=>'人工费','shiid'=>2],
            'ji' =>  ['name'=>'机械费','shiid'=>3],
            'fen' =>  ['name'=>'分包费','shiid'=>4],
            'cuo' =>  ['name'=>'措施费','shiid'=>5],
            'guan' =>  ['name'=>'项目费用','shiid'=>0],
        ];

        foreach ($arr as $k=>&$v){
            $topid = EnginBudsubModel::where(['comid'=>$this->userinfo['comid'],'pid'=>0,'name'=>$v['name']])->value('id');
            $v['ids'] = EnginBudsubModel::where(['comid'=>$this->userinfo['comid'],'topid'=>$topid])->column('id');
        }

        $data['data'] = EnginBudgetModel::alias('bud')
            ->field('bud.*,e.name as enginname')
            ->join('engin e','e.id=bud.enginid')
            ->where($where)
            ->order('bud.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key)use($arr){
                $item['heji_yusuan'] = 0;
                $item['heji_shi'] = 0;
                $item['heji_chao'] = 0;


                foreach ($arr as $kk=>$vv){
                    $item[$kk.'_yusuan'] = EnginBudgetListModel::where(['budid'=>$item['id']])
                        ->where('subid','in',$vv['ids'])->sum('money');
                    if($kk == 'guan'){
                        $item[$kk.'_shi'] = PaymentBaoModel::where(['deleted_user'=>0,'isturn'=>1])
                            ->where(['enginid'=>$item['enginid']])->where('status','in',[0,1])
                            ->sum('money');
                    }else{
                        $item[$kk.'_shi'] = PaymentEnginModel::where(['deleted_user'=>0,'isturn'=>1])
                            ->where(['enginid'=>$item['enginid'],'budid'=>$vv['shiid']])->where('status','in',[0,1])
                            ->sum('money');
                    }
                    $item[$kk.'_chao'] = $item[$kk.'_shi'] - $item[$kk.'_yusuan'];

                    $item['heji_yusuan'] += $item[$kk.'_yusuan'];
                    $item['heji_shi'] = $item[$kk.'_shi'];
                    $item['heji_chao'] = $item[$kk.'_chao'];

                    $item[$kk.'_chao'] = $item[$kk.'_chao'] < 0 ? '' : $item[$kk.'_chao'];
                }

                $item['heji_chao'] = $item['heji_chao'] < 0 ? '' : $item['heji_chao'];
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('engin_cheng_zhi');
        return outputJson(2000,lang('code_2000'),$data);
    }

    public function list_zhi_cheng_fen(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['deleted_user','=', 0];
        $where[] = ['comid','=',$this->userinfo['comid']];
        $where[] = ['isturn','=',1];
        $where[] = ['status','=',1];

        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['name','like', '%'.$param['name'].'%'];
        }

        $data['data'] = EnginModel::where($where)
            ->order('id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['cai_con'] = ContractCaiModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id'],'caihetype'=>1])->where('status','in',[0,1])->sum('money');
                $item['cai_stuffru'] = StuffRuModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id']])->where('status','in',[0,1])->sum('money');
                $item['cai_stuffjie'] = StuffJieModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id']])->where('status','in',[0,1])->sum('money');
                $item['cai_fuku'] = PaymentEnginModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id'],'budid'=>1])->where('status','in',[0,1])->sum('money');

                $item['ren_con'] = ContractCaiModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id'],'caihetype'=>2])->where('status','in',[0,1])->sum('money');
                $item['ren_labourshen'] = LabourShenModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id']])->where('status','in',[0,1])->sum('money');
                $item['ren_labourjie'] = LabourJieModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id']])->where('status','in',[0,1])->sum('money');
                $item['ren_labourling'] = LabourLingModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id']])->where('status','in',[0,1])->sum('money');
                $item['ren_fuku'] = PaymentEnginModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id'],'budid'=>2])->where('status','in',[0,1])->sum('money');

                $item['zu_con'] = ContractCaiModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id'],'caihetype'=>3])->where('status','in',[0,1])->sum('money');
                $item['zu_devicejie'] = DeviceJieModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id']])->where('status','in',[0,1])->sum('money');
                $item['zu_labourlin'] = DeviceLinModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id']])->where('status','in',[0,1])->sum('money');
                $item['zu_fuku'] = PaymentEnginModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id'],'budid'=>3])->where('status','in',[0,1])->sum('money');

                $item['fen_con'] = ContractCaiModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id'],'caihetype'=>4])->where('status','in',[0,1])->sum('money');
                $item['fen_subbaoshen'] = SubbaoShenModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id']])->where('status','in',[0,1])->sum('money');
                $item['fen_subbaojie'] = SubbaoJieModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id']])->where('status','in',[0,1])->sum('money');
                $item['fen_fuku'] = PaymentEnginModel::where(['deleted_user'=>0,'isturn'=>1,'enginid'=>$item['id'],'budid'=>4])->where('status','in',[0,1])->sum('money');

                return $item;
            })->toArray();

        return outputJson(2000,lang('code_2000'),$data);
    }

    public function list_guan_cheng_fen(Request $request){
        $param = $request->post();

        $where[] = ['deleted_user','=', 0];
        $where[] = ['comid','=',$this->userinfo['comid']];
        $where[] = ['isturn','=',1];
        $where[] = ['status','in',[0,1]];

        if(isset($param['enginid']) && !empty($param['enginid'])){
            $where[] = ['bao.enginid','=',$param['enginid']];
        }

        $data['enginid'] = EnginModel::field('id as value,name')->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
            ->where(['isturn'=>1,'status'=>1])->select()->toArray();
        $data['is_enginid'] = isset($param['enginid']) ? $param['enginid'] : '';


        $baolist = PaymentBaoModel::field('budid,money as zhimoney')
            ->where($where)
            ->select()->toArray();

        $topid = EnginBudsubModel::where(['name'=>'项目费用'])->value('id');
        $kemu = EnginBudsubModel::field('id,name,pid')->where(['comid'=>$this->userinfo['comid'],'status'=>1])
            ->where("id=".$topid." or topid=".$topid)->select()->toArray();
        foreach ($kemu as &$v){
            $v['zhimoney'] = 0;
            $v['son'] = EnginBudsubModel::where(['comid'=>$this->userinfo['comid'],'status'=>1,'pid'=>$v['id']])->column('id');

            foreach ($baolist as $bao){
                if($bao['budid'] == $v['id']){
                    $v['zhimoney'] += $bao['zhimoney'];
                }else{
                    if(in_array($bao['budid'], $v['son'])){
                        $v['zhimoney'] += $bao['zhimoney'];
                    }
                }
            }
        }

        $data['data'] = array2tree($kemu, 'id', 'pid', 'children');

        return outputJson(2000,lang('code_2000'),$data);
    }

    public function list_engin_budbian(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['bud.deleted_user','=', 0];
        $where[] = ['bud.comid','=',$this->userinfo['comid']];
        $where[] = ['bud.isturn','=',1];
        $where[] = ['bud.status','in',[0,1]];
        $where[] = ['bud.budgetid','=',$param['budgetid']];

        $data['data'] = EnginBudbianModel::alias('bud')
            ->field('bud.*,e.name as enginname,budget.name as budget_name')
            ->join('engin_budget budget','budget.id=bud.budgetid')
            ->join('engin e','e.id=budget.enginid')
            ->where($where)
            ->where((new MenuService())->get_miss_where('engin_budbian', 'bud'))
            ->order('bud.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['type_name'] = '';
                if($item['type'] == 1){
                    $item['type_name'] = '调整';
                }elseif($item['type'] == 2){
                    $item['type_name'] = '增项';
                }elseif($item['type'] == 3){
                    $item['type_name'] = '调整及增项';
                }

                return $item;
            })->toArray();

        $data['budgetinfo'] = EnginBudgetModel::where(['id'=>$param['budgetid']])->find();
        $data['butauth'] = (new MenuService())->get_butauth('engin_budbian');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_engin_budbian(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['budgetid'])){
                return outputJson(4000, '请选择预算主题');
            }
            $param['enginid'] = EnginBudgetModel::where(['id'=>$param['budgetid']])->value('enginid');

            $param['comid'] = $this->userinfo['comid'];
            $param['status'] = 1;
            $param['isturn'] = 1;
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            $param['deptid'] = $this->userinfo['deptid'];
            $param['chanid'] = (new UserService())->get_user_chanid();


            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            $tiaolist = array_filter($param['tiaolist']);
            unset($param['tiaolist']);
            $zenglist = array_filter($param['zenglist']);
            unset($param['zenglist']);

            if($param['type'] == 1 || $param['type'] == 3){
                if(count($tiaolist) < 1){
                    return outputJson(4000, '请输入调整明细');
                }
            }
            if($param['type'] == 2 || $param['type'] == 3){
                if(count($zenglist) < 1){
                    return outputJson(4000, '请输入增项明细');
                }
            }



            Db::startTrans();
            try {
                $id = EnginBudbianModel::insertGetId($param);

                if($param['type'] == 1 || $param['type'] == 3){
                    foreach($tiaolist as $vv){
                        $vv['budid'] = $id;
                        EnginBudbianListModel::insert($vv);
                    }
                }

                if($param['type'] == 2 || $param['type'] == 3){
                    foreach($zenglist as $vv){
                        $vv['budid'] = $id;
                        EnginBudbianListModel::insert($vv);
                    }
                }

                (new EnginRelevan())->vate_engin_budget_list($id);



                (new OptService())->relation_file($files,'engin_budbian',$id);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'engin_budbian', $id);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'engin_budbian', $id, '成本预算变更');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $budgetid = $request->param('budgetid', 0, 'int');
            $data = EnginBudgetModel::get_info_by_pk($budgetid);

            $engininfo = EnginModel::get_info_by_pk($data['enginid']);
            $data['engininfo'] = $engininfo;
            $data['files'] = (new OptService())->get_file('engin_budbian');
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function del_engin_budbian(Request $request){
        $param = $request->post();
        $data = EnginBudbianModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            FlowBillModel::where(['id'=>$data['billid']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            EnginBudbianModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'engin_budbian', $data['id'], '成本预算变更');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function show_engin_budbian(Request $request){
        $id = $request->post('id', 0, 'int');
        $data['data'] = EnginBudbianModel::get_info_by_pk($id);
        if(!$data['data']){
            return outputJson(4000, lang('code_4000'));
        }

        $data['data']['type_name'] = '';
        if($data['data']['type'] == 1){
            $data['data']['type_name'] = '调整';
        }elseif($data['data']['type'] == 2){
            $data['data']['type_name'] = '增项';
        }elseif($data['data']['type'] == 3){
            $data['data']['type_name'] = '调整及增项';
        }

        $data['engininfo'] = (new EnginService())->get_engin_showinfo($data['data']['enginid']);
        $data['budgetinfo'] = EnginBudgetModel::where(['id'=>$data['data']['budgetid']])->find();

        $tiaolist = EnginBudbianListModel::where(['budid'=>$data['data']['id']])->where('listid','gt',0)->select()->toArray();
        $data['tiaolist'] = $tiaolist;

        $zenglist = EnginBudbianListModel::where(['budid'=>$data['data']['id']])->where('listid','=',0)->select()->toArray();
        $data['zenglist'] = $zenglist;


        $data['files'] = (new OptService())->get_file('engin_budbian', $data['data']['id']);
        $data['billinfo'] = (new FlowService())->get_flow_show_info($data['data']['billid']);
        return outputJson(2000,lang('code_2000'), $data);
    }




}
